#!/bin/sh

BASE_DIR=$(dirname $(dirname $(readlink -f $0)))
SVN_REPO_URL=https://pytvshows-plus.googlecode.com/svn
REL_STRING_FILE=src/pytvshows-plus
SANDBOX="/tmp/pts-rel-$(date --rfc-3339=date)"
SETUP_PY=setup.py

(rm -rf ${SANDBOX} && mkdir -p ${SANDBOX}) || exit -1

echo -n "Enter release version string: "
read REL_STRING
echo -n "Enter SVN username: "
read SVN_USER

cd ${SANDBOX}
svn checkout ${SVN_REPO_URL}/trunk/ pytvshows-plus --username ${SVN_USER} || exit -1
cd pytvshows-plus
sed -i "s/__version__[ ]*=.*/__version__ = '${REL_STRING}'/" ${REL_STRING_FILE} || exit -1
sed -i "s/version=.*,/version='${REL_STRING}',/" ${SETUP_PY} || exit -1
dch --newversion ${REL_STRING} || exit -1
if [ "" != "$(svn diff)" ]
then
    echo "Updating version string and changelog and creating release tag ..."
    svn commit -m "Bump version for ${REL_STRING} release" || exit -1
    svn copy -m "Release version ${REL_STRING}" "${SVN_REPO_URL}/trunk" "${SVN_REPO_URL}/tags/releases/${REL_STRING}" || exit -1
fi

echo "Creating release packages ..."
cd ${SANDBOX}
svn export ${SVN_REPO_URL}/tags/releases/${REL_STRING} ${SANDBOX}/pytvshows-plus-${REL_STRING} || exit -1
tar -zcf pytvshows-plus-${REL_STRING}.tar.gz pytvshows-plus-${REL_STRING} || exit -1

ln -s pytvshows-plus-${REL_STRING}.tar.gz pytvshows-plus_${REL_STRING}.orig.tar.gz
cd pytvshows-plus-${REL_STRING}
# Requires that DEBFULLNAME and DEBEMAIL are set and match a key in the GPG
# keyring (`gpg --list-keys`)
debuild binary-indep || exit -1
cd ..

echo "Uploading release packages ..."
wget "http://support.googlecode.com/svn/trunk/scripts/googlecode_upload.py" || exit -1
python ./googlecode_upload.py --project=pytvshows-plus --summary="Release ${REL_STRING} (all platforms)" --labels=Featured,Type-Archive,OpSys-All --user=${SVN_USER} pytvshows-plus-${REL_STRING}.tar.gz || exit -1
python ./googlecode_upload.py --project=pytvshows-plus --summary="Release ${REL_STRING} (Debian/Ubuntu)" --labels=Featured,Type-Package,OpSys-Linux,LinuxDistro-Debian --user=${SVN_USER} pytvshows-plus_${REL_STRING}_all.deb || exit -1

cd /tmp
rm -rf ${SANDBOX}
